package util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateSessionFactory {
	private static final String CONFIG_FILE_PATH = "/config/hibernate.cfg.xml";
	private static final ThreadLocal<Session> threadlocal = new ThreadLocal<Session>();
	private static final Configuration cfg = new Configuration();
	private static SessionFactory sessionFractory;
	
	public static Session currentSession(){
		Session session = (Session) threadlocal.get();
		if(session==null || session.isOpen()){
			if(sessionFractory==null){
				cfg.configure(CONFIG_FILE_PATH);
				sessionFractory = cfg.buildSessionFactory();
			}
			session = sessionFractory!=null?sessionFractory.openSession():null;
			threadlocal.set(session);
		}
		return session;
	}
	
	public static void closeSession(){
		Session session = threadlocal.get();
		threadlocal.set(null);
		if(session!=null){
			session.close();
		}
	}
}
